"""Archive Controller"""
from arkivo.lib.base import BaseController
from tg import expose, flash
from pylons.i18n import ugettext as _
from tg import redirect, validate
from tg.exceptions import HTTPNotFound
#from arkivo.model import DBSession

from datetime import datetime, timedelta

from arkivo import model
from arkivo.lib.smartmessage import SmartMessageHelper

class ArchiveController(BaseController):

    @expose('arkivo.templates.archive')
    def default(self, *args, **kw):
        args = list(args)
        try:
            service = args.pop(0)
        except IndexError:
            raise redirect("/")
        
        try:
            name = args.pop(0)
        except IndexError:
            raise HTTPNotFound("No Channel specified").exception
        
        ptype = None
        message_select = None
        arc_date = None
        
        channel = model.Channel.by_name_and_service(name, service)
        if not channel:
            raise HTTPNotFound("Channel not found").exception
            
        try:
            urldate = [int(arg) for i,arg in enumerate(args) if i <3]
        except ValueError:
            raise HTTPNotFound("Invalid date strings").exception
            
        messages = []
        
        if len(urldate) > 0:
            # Check for a date.
            if len(urldate) == 3:
                try:
                    _url_datetime = datetime(urldate[0], urldate[1], urldate[2])
                except ValueError:
                    raise HTTPNotFound("Invalid date").exception
                
                start_date = _url_datetime
                end_date = _url_datetime + timedelta(1)
                
                ptype = "Archive for %s" % _url_datetime.strftime('%d %B, %Y')
                messages = channel.messages_by_datetime(start_date, end_date)
                arc_date = _url_datetime
        else:
            messages = channel.last_messages()
            ptype = "Last 100 messages"
            
        helper = SmartMessageHelper()
        messages = [helper(m) for m in messages]
        
        if messages:
            last_date = messages[-1].datestr
            first_date = messages[0].datestr
        else:
            last_date = None
            first_date = None
            
        return dict(service=channel.service,
                    channel=channel,
                    messages=messages,
                    ptype=ptype,
                    arc_date=arc_date,
                    first_date=first_date,
                    last_date=last_date)